<template>
  <view>
    <view class="top">
      <text
        v-for="(item,index) in navTab"
        :key="index"
        @tap="currentTab(index)"
        :class="active==index ? 'top-active' : ''"
      >{{item}}</text>
    </view>
    <view v-if="active==0" style="padding-top:90rpx">
      <view v-if="total>0">
        <view class="card2" v-for="(item,index) in couponList" :key="'cou_'+index">
          <view class="card2-box" @tap="choiceCoupon(item)">
            <view class="t1">{{item.carCoupon.couponName}}</view>
            <view class="t2">优惠金额{{item.carCoupon.deduction}}元</view>
            <!-- <view class="t2 t2-red">明天即将过期</view> -->
            <view class="t3">{{item.startDate}}~{{item.endDate}}</view>
            <view class="t3">每天{{item.carCoupon.useStartTime}} ~ {{item.carCoupon.useEndTime}}可用</view>
            <view class="t4">满{{item.carCoupon.useStartPrice}}元可用</view>
            <!-- <view class="t5">
              <text style="font-size:28px">￥</text>
              <text>{{item.carCoupon.deduction}}</text>
            </view>-->
            <image src="../../image/choice.png" v-if="item.id==id&&changed" />
            <image src="../../image/notchoice.png" v-else />
          </view>
        </view>
        <view v-if="loading" class="moreText">
          <text>玩命的加载中...</text>
        </view>
        <view v-if="!loading&&!hasMore" class="moreText">
          <text>没有更多内容了</text>
        </view>
      </view>
      <view v-else>
        <empty :emptyText="'暂无可使用的优惠券哦~~~'" />
      </view>
    </view>
    <!--过期-->
    <view v-if="active == 1" style="padding-top:90rpx">
      <view v-if="outTotal>0">
        <view class="card2 filter" v-for="(item,index) in outcouponList" :key="index">
          <view class="card2-box">
            <view class="t1">{{item.carCoupon.couponName}}</view>
            <view class="t2">{{item.startDate}}-{{item.endDate}}</view>
            <view class="t3">临时停车抵扣券</view>
          </view>
        </view>
        <view v-if="loading" class="moreText">
          <text>玩命的加载中...</text>
        </view>
        <view v-if="!loading&&!hasMore" class="moreText">
          <text>没有更多内容了</text>
        </view>
      </view>

      <empty :emptyText="'暂无过期优惠券哦~~~'" v-else />
    </view>
    <view style="height:100px"></view>
    <view class="footer">
      <view class="footer-p1">
        已选{{discountAmount==0?'0':'1'}}张，可减
        <text style="color:#EB5757">{{discountAmount}}元</text>
      </view>
      <view class="footer-btn" @tap="goBack">{{id==0?'返回':'确定'}}</view>
    </view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import { setGlobalData, getGlobalData } from "../../globalData.js";
import authorize from "../../authorize.js";
import empty from "../../components/empty/empty";
import "./counponList.less";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
// pages/card/card.js
export default {
  data() {
    return {
      apiBaseUrl: process.env.IOParking.API_HOST, //请求头
      navTab: ["未过期", "已过期"],
      changed: true,
      showIndex: 0,
      parkId: 0,
      time: [],
      couponList: [],
      outcouponList: [],
      outTotal: 0,
      total: 0,
      loading: true,
      isFirstLoad: true,
      pageIndex: 1,
      pageSize: 20,
      id: 0,//优惠券Id
      carNo: "",
      discountAmount: 0,
      money: 0,
      active: 0,
      hasPhone: true,
      hasMore: false
    };
  },
  mixins: [authorize],
  components: { empty },
  onLoad: function(options) {
    api.bury("userClickPayButton", {
      time: new Date().valueOf(),
      loginState: false
    });
    console.log(options); //parkId=1&carNo=蒙V12345&parkingCode=&channelCode=money&__key_=16225289774313
    this.parkId = options.parkId;
    this.parkingCode = options.parkingCode ? options.parkingCode : "";
    this.channelCode = options.channelCode ? options.channelCode : "";
    this.carNo = options.carNo ? options.carNo : "";
    this.money = options.money ? options.money : 0;
    if (getGlobalData("mobile")) {
      this.mobile = getGlobalData("mobile");
    }
    if (getGlobalData("openId")) {
      this.openId = getGlobalData("openId");
    }
    this.unexpiredData();
  },
  onPullDownRefresh() {
      this.pageIndex = 1;
      this.isFirstLoad = true;
      if (this.currentTab == "0") {
        this.unexpiredData();
      } else {
        this.outData();
      }
      Taro.stopPullDownRefresh(); //结束刷新
    },
    onReachBottom() {
      //触发了上拉加载，做些什么
      let that = this;
      that.pageIndex = that.pageIndex + 1;
      that.isFirstLoad = false;
      if (that.currentTab == "0") {
        that.unexpiredData();
      } else {
        that.outData();
      }
    },
  methods: {
    unexpiredData: function() {
      Taro.showLoading({
        title: "加载中",
        mask: true
      });
      var that = this;
      var base = that.apiBaseUrl;
      that.setDataloading = true;
      Taro.showLoading({
        title: "加载中",
        mask: true
      });
      console.log("优惠券读取的信息：", {
        mobile: getGlobalData("mobile") || "",
        wxOpenId: getGlobalData("openId"),
        parkId: that.parkId
      });
      Taro.request({
        url: base + "/carcoupon/pagelist",
        data: {
          pageIndex: that.pageIndex,
          pageSize: that.pageSize,
          filter: {
            mobile: getGlobalData("mobile") || "",
            wxOpenId: getGlobalData("openId"),
            parkId: that.parkId
          }
        },
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "POST",
        success(res) {
          Taro.hideLoading();
          that.loading = false;
          if (res.data.isSuccess) {
            if (that.isFirstLoad) {
              //初始化
              that.total = res.data.data.total;
              that.couponList = res.data.data.list;
              
                //默认可用的第一个
                that.couponList.some(item => {
                  console.log(that.handleCoupon(item));
                  if (that.handleCoupon(item) == 1) {
                    console.log(item);
                    that.id = item.id;
                    that.discountAmount = item.carCoupon.deduction;
                    return true;
                  }
                });
              
            }else{
               that.couponList = that.couponList.concat(
                res.data.data.list
              );
            }
            if (res.data.data.list.length < that.pageSize) {
              that.hasMore = false;
            }
            that.total = res.data.data.total;
          }
        }
      });
    },
    outData() {
      Taro.showLoading({
        title: "加载中",
        mask: true
      });
      var that = this;
      var base = that.apiBaseUrl;
      Taro.request({
        url: base + "/carcoupon/pagelistdisable",
        data: {
          pageIndex: that.pageIndex,
          pageSize: that.pageSize,
          filter: {
            mobile: getGlobalData("mobile"),
            wxOpenId: getGlobalData("openId"),
            parkId: that.parkId
          }
        },
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "POST",
        success(res) {
          Taro.hideLoading();
          that.loading = false;
          if (res.data.isSuccess) {
            if (that.isFirstLoad) {
              //初始化
              that.outcouponList = res.data.data.list;
            } else {
              //加载更多追加
              that.outcouponList = that.outcouponList.concat(
                res.data.data.list
              );
            }
            if (res.data.data.list.length < that.pageSize) {
              that.hasMore = false;
            }
            that.outTotal = res.data.data.total;
          }
        }
      });
    },
    choiceCoupon(item) {
      var date = new Date();
      let year = date.getFullYear(); //获取完整的年份(4位)
      let month = date.getMonth() + 1; //获取当前月份
      month = month < 10 ? "0" + month : month + "";
      let day = date.getDate(); //获取当前日(1-31)
      day = day < 10 ? "0" + day : day + "";
      let time = year + "/" + month + "/" + day;
      let useStartTime = time + " " + item.carCoupon.useStartTime + ":00";
      let useEndTime = time + " " + item.carCoupon.useEndTime + ":00";
      console.log(useStartTime,new Date() ,useEndTime);
      useStartTime = new Date(useStartTime.replace(/-/g, "/")).valueOf();
      useEndTime = new Date(useEndTime.replace(/-/g, "/")).valueOf();
      let nowTime = new Date().valueOf();

      if (nowTime < useStartTime || nowTime > useEndTime) {
        console.log("不可领取");
        Taro.showToast({
          title: "该时段不可使用",
          icon: "error",
          duration: 1000,
          mask: true
        });
        return;
      }
      if (+this.money < +item.carCoupon.useStartPrice) {
        Taro.showToast({
          title: "未达到满减金额",
          icon: "error",
          duration: 1000,
          mask: true
        });
        return;
      }
      if (this.id !== item.id) {
        this.changed = true;
      } else {
        this.changed = !this.changed;
      }
      this.id = item.id;
      this.discountAmount = item.carCoupon.deduction;
      if(!this.changed){
        this.discountAmount=0;
        this.id=''
      }
    },
    choiceNotCoupon() {
      this.id = 0;
      this.discountAmount = 0;
    },
    handleCoupon(item) {
      var flag = 1;
      var date = new Date();
      let year = date.getFullYear(); //获取完整的年份(4位)
      let month = date.getMonth() + 1; //获取当前月份
      month = month < 10 ? "0" + month : month + "";
      let day = date.getDate(); //获取当前日(1-31)
      day = day < 10 ? "0" + day : day + "";
      let time = year + "/" + month + "/" + day;
      let useStartTime = time + " " + item.carCoupon.useStartTime + ":00";
      let useEndTime = time + " " + item.carCoupon.useEndTime + ":00";
      console.log(useStartTime, useEndTime);
      useStartTime = new Date(useStartTime.replace(/-/g, "/")).valueOf();
      useEndTime = new Date(useEndTime.replace(/-/g, "/")).valueOf();
      let nowTime = new Date().valueOf();

      if (nowTime < useStartTime || nowTime > useEndTime) {
        flag = 0;
      }
      if (+this.money < +item.carCoupon.useStartPrice) {
        flag = 0;
      }
      return flag;
    },
    goBack() {
      Taro.reLaunch({
        url:
          "../trafficManage/goPay?id=" +
          this.id +
          "&discountAmount=" +
          this.discountAmount +
          "&carNo=" +
          this.carNo +
          "&parkingCode=" +
          this.parkingCode +
          "&channelCode=" +
          this.channelCode
      });
    },
    currentTab: function(e) {
      if (this.active == e) {
        return;
      }
      this.active = e;
      this.hasMore = true;
      this.loading = true;
      this.isFirstLoad = true;
      if (this.active == "0") {
        this.pageIndex = 1;
        this.unexpiredData();
      } else {
        this.pageIndex = 1;
        this.outData();
      }
    },
    panel: function(e) {
      if (e != this.showIndex) {
        this.showIndex = e;
      } else {
        this.showIndex = 0;
      }
    }
  }
};
</script>
